<?php
/**
 * account actions.
 *
 * @package    IPLIFE
 * @subpackage account
 * @author     alexey.shapran@gmail.com
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */

if (!defined('FORUM_ROOT'))
define('FORUM_ROOT', sfConfig::get('sf_web_dir').DIRECTORY_SEPARATOR.'forum'.DIRECTORY_SEPARATOR);

//require FORUM_ROOT.'include/common.php';

//require(FORUM_ROOT.'include'.DIRECTORY_SEPARATOR.'dblayer'.DIRECTORY_SEPARATOR.'common_db.php' );

require(FORUM_ROOT.'config.php' );
require(FORUM_ROOT.'include'.DIRECTORY_SEPARATOR.'functions.php' );
//require(FORUM_ROOT.'admin'.DIRECTORY_SEPARATOR.'settings.php' );
//$forum_root = sfConfig::get('sf_web_dir').DIRECTORY_SEPARATOR.'forum'.DIRECTORY_SEPARATOR ;
//
//require $forum_root.'include/common.php';
//
//			require($forum_root.'include'.DIRECTORY_SEPARATOR.'dblayer'.DIRECTORY_SEPARATOR.'common_db.php' );
//			require(sfConfig::get('sf_web_dir').DIRECTORY_SEPARATOR.'forum'.DIRECTORY_SEPARATOR.'include'.DIRECTORY_SEPARATOR.'functions.php' );


class accountActions extends sfActions
{
	public function postExecute()
	{
		$this->setLayout('2columns-right');
	}

	public function executeDownloadlist(sfWebRequest $request)
	{
		$categories = Category::getAllCategories();

		$path = sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR;
		$filename = 'categories.html';

		if(file_exists($path.$filename))
		{
			$file = fopen($path.$filename, 'w+');
			fwrite($file, '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <html><head></head><body>');

			fwrite($file, '<ul style="font-size:12px; padding:0 20px;">'.$this->doSomething($categories, NULL, 0, 2, false ).'</ul>');
		}
		fwrite($file, '<body></html>');
		fclose($file);

		header('Content-type: text/html;');
		header('Content-Disposition: attachment; filename=categories.html');
		$x = fread(fopen($path.$filename, "rb"), filesize($path.$filename));
		echo $x;
		exit;

	}

	public function executeIndex(sfWebRequest $request)
	{
		$user_id = $request->getParameter('user_id',$this->getUser()->getId());
		$this->account = Doctrine::getTable('SfGuardUser')->find($user_id);
		if(!$this->account)
		$this->redirect('@homepage');
	}

	public function executeRegistration(sfWebRequest $request)
	{
		$this->form = new RegistrationForm();
	}

	public function executeCreate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod('post'));
		$this->form = new RegistrationForm();
		$this->processForm($request,$this->form);
		$this->setTemplate('registration');
	}

	public function executeEdit(sfWebRequest $request)
	{
		$account = Doctrine::getTable('sfGuardUser')->find($this->getUser()->getId());//, sprintf('User does not exist (id:%s).', $request->getParameter('id')));
		$this->forward404Unless($account);
		$this->form = new RegistrationForm($account);
		unset($this->form['nickname']);
		$this->setTemplate('edit');
	}

	public function executeUpdate(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod('post') || $request->isMethod('put'));
		$sf_guard_user = $request->getParameter('sf_guard_user');
		$this->forward404Unless($account = Doctrine::getTable('SfGuardUser')->find($sf_guard_user['id']));

		$this->form = new RegistrationForm($account);
		unset($this->form['nickname']);
		$this->processForm($request, $this->form);
		$this->setTemplate('edit');
	}

	public function executeShowmyproducts(sfWebRequest $request)
	{
		$filename = sfConfig::get('sf_upload_dir').DIRECTORY_SEPARATOR.'usd.txt';
		if(is_file($filename))
		{
			$file=fopen($filename, 'r+');
			$this->course = fread($file, 1000) / 100; // for 1 usd
			fclose($file);
		}
		else $this->course = 1;

		$max_own_products_on_page = 20;
		if(!$this->getUser()->isAuthenticated())
		$this->redirect('default/index');
		$allmyprods = Product::retrieveMyProductsQuery($this->getUser()->getGuardUser()->getId());

		$prodspersellerownpage = ( $request->getParameter('page',1)!='all'? $max_own_products_on_page : count($allmyprods->execute()) );

		$this->pager = new sfDoctrinePager('Product',$prodspersellerownpage);
		$this->pager->setQuery($allmyprods);
		$this->pager->setPage($request->getParameter('page',1));
		$this->pager->init();
	}

	public function executeAddproduct(sfWebRequest $request) {
		$this->form = new ProductForm();
	}

	public function executeSubmitproduct(sfWebRequest $request) {

		$this->forward404Unless($request->isMethod('post'));
		$this->form = new ProductForm();

		$imgfile = $request->getFiles('img');

		$this->form->bind(array(
      'category_id' => $request->getParameter('category_id'),
      'title'       => $request->getParameter('title'),
      'short'       => $request->getParameter('short'),
      'body'        => $request->getParameter('body'),
      'img'         => $request->getParameter('img'),
      'price'       => $request->getParameter('price'),
	  'price_usd'   => $request->getParameter('price_usd'),
      'artikul'     => $request->getParameter('artikul'),
      'rank'        => $request->getParameter('rank'),
      'user_id'     => $this->getUser()->getGuardUser()->getId(),
	  '_csrf_token' => $request->getParameter('_csrf_token')
		),			array( 'img'=>$imgfile   )   );

		if($this->form->isValid()){
			$this->form->save();
			$this->redirect('account/showmyproducts');
		}

		$this->setTemplate('addproduct');
	}


	public function executeSaveproduct(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod('post'));

		$prod_id = $request->getParameter('id');
		$user_id = $this->getUser()->getGuardUser()->getId();
		$this->product = Product::retrieveMyProductToEdit($prod_id, $user_id);
		$this->form = new ProductForm($this->product);

		$imgfile = $request->getFiles('img');

		$this->form->bind(array(
      'category_id' => $request->getParameter('category_id'),
      'title'       => $request->getParameter('title'),
      'short'       => $request->getParameter('short'),
      'body'        => $request->getParameter('body'),
      'img'         => $request->getParameter('img'),
      'price'       => $request->getParameter('price'),
	  'price_usd'   => $request->getParameter('price_usd'),
      'artikul'     => $request->getParameter('artikul'),
      'rank'        => $request->getParameter('rank'),
      'user_id'     => $this->getUser()->getGuardUser()->getId(),
	  '_csrf_token' => $request->getParameter('_csrf_token')
		),			array( 'img'=>$imgfile   )   );

		if($this->form->isValid()){
			$this->form->save();
			$this->redirect('account/showmyproducts');
		}

		$this->setTemplate('editproduct');
	}


	public function executeDeleteproduct(sfWebRequest $request)
	{
		$pr_id = $request->getParameter('prid');
		Product::deleteMyProductByIdAndUserId($pr_id, $this->getUser()->getGuardUser()->getId());

		$prevpage = $_SERVER['HTTP_REFERER'];
		$this->redirect($prevpage);
	}

	public function executeEditproduct(sfWebRequest $request)
	{
		$prod_id = $request->getParameter('prid');
		$user_id = $this->getUser()->getGuardUser()->getId();
		$this->product = Product::retrieveMyProductToEdit($prod_id, $user_id);
		$this->form = new ProductForm($this->product);
	}
	public function executeUploadprices(sfWebRequest $request){
		$this->form = new UploadExcelForm();
	}

	public function executeUploadprice(sfWebRequest $request)
	{
		$price = $request->getFiles('price');
		$user_id = $this->getUser()->getGuardUser()->getId();
		$file_to_include = $price['tmp_name'];

		$allow_url_override = 1; // Set to 0 to not allow changed VIA POST or GET
		if(!$allow_url_override || !isset($file_to_include))
		{
			$file_to_include = "price.xls";
		}
		if(!$allow_url_override || !isset($max_rows))
		{
			$max_rows = 0; //USE 0 for no max
		}
		if(!$allow_url_override || !isset($max_cols))
		{
			$max_cols = 8; //USE 0 for no max
		}
		if(!$allow_url_override || !isset($debug))
		{
			$debug = 0;  //1 for on 0 for off
		}
		if(!$allow_url_override || !isset($force_nobr))
		{
			$force_nobr = 1;  //Force the info in cells not to wrap unless stated explicitly (newline)
		}

		require_once 'Excel'.DIRECTORY_SEPARATOR.'reader.php';

		$data = new Spreadsheet_Excel_Reader();
		$data->setOutputEncoding('utf8');
		$data->read($file_to_include);
		$this->ers = array();

		for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++)
		{
			list($nulEl, $art, $tit, $cat, $pr, $pr_u, $ran, $al, $bod) = $data->sheets[0]['cells'][$i] ;
			$item = array($art, $tit, $cat, $pr, $pr_u, $ran, $al, $bod);
			$answer = Product::insertProductItem($item, $user_id);
			if ($answer!='Ok')
			{
				$this->ers[] = $answer.$i;
			}
		}

		$this->getUser()->setFlash('uploaded', (!count($this->ers) ? 'Экспортировано успешно' : 'Экспортировано с ошибками') );
		$this->form = new UploadExcelForm();
		$this->setTemplate('uploadprices');
	}

	public function executeMyreleases(sfWebRequest $request)
	{
		$ownreleasesonpage = 20;
		if($this->getUser()->isAuthenticated())
		{
			$this->pager = new sfDoctrinePager('Reliz', $ownreleasesonpage);
			$this->pager->setQuery(Reliz::getMyReleases($this->getUser()->getGuardUser()->getId()));
			$this->pager->setPage($request->getParameter('page','1'));
			$this->pager->init();
		}
		else $this->redirect('default/index');
	}
	public function executeAddrelease(sfWebRequest $request)
	{
		$this->form = new RelizFrontForm();
	}

	public function executeEditrelease(sfWebRequest $request)
	{
		if($this->getUser()->isAuthenticated())
		{
			$myrelease = Reliz::getMyReleaseToEdit($request->getParameter('relid'), $this->getUser()->getGuardUser()->getId());
			$this->form = new RelizFrontForm($myrelease);
		}
		else $this->redirect('default/index');
	}
	public function executeDeleterelease(sfWebRequest $request)
	{
		if($this->getUser()->isAuthenticated())
		{
			Reliz::deleteMyRelease($request->getParameter('relid'), $this->getUser()->getGuardUser()->getId());
			$this->redirect('account/myreleases');
		}
		else
		$this->redirect('default/index');
	}

	public function executeSubmitrelease(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod('post'));

		$relid = $request->getParameter('id');
		if($relid == NULL)
		$this->form = new RelizFrontForm();
		else
		{
			$this->form = new RelizFrontForm( Reliz::getMyReleaseToEdit($relid, $this->getUser()->getGuardUser()->getId()) );
		}

		$this->form->bind(array(
							      'category_id'         => $request->getParameter('category_id'),
							      'user_id'             => $this->getUser()->getGuardUser()->getId(),
							      'alias'               => $request->getParameter('alias')? $request->getParameter('alias') : Reliz::getMaxIdFromReleases(),
							      'title'               => $request->getParameter('title'),
							      'short'               => $request->getParameter('short'),
							      'body'                => $request->getParameter('body'),
								  'id'					=> $relid,
								  'is_published'		=> '0',
							      'keywords'            => $request->getParameter('keywords'),						
							      'description'         => $request->getParameter('short'),
							      'tags'                => $request->getParameter('keywords'),
							      'image'               => $request->getParameter('image'),
								  'image_text'			=> $request->getParameter('title'),
							      'is_allowed_comments' => $request->getParameter('is_allowed_comments'),
								  '_csrf_token'		=> $request->getParameter('_csrf_token'),
		),				 array('image'=>$request->getFiles('image')));

		if($this->form->isValid())
		{
			$this->form->save();
			$this->getUser()->setFlash('release', 'Ваш релиз отправлен администратору сайта. В случае, если он будет одобрен, его опубликуют.');
			$this->redirect('account/editrelease?relid='.$this->form->getObject()->getId());
		}
		else {
			$this->setTemplate('editrelease');
		}
	}

	public function executeHowtoupload(sfWebRequest $request)
	{

	}

	public function executeBlogrequest(sfWebRequest $request)
	{
		$this->getUser()->getGuardUser()->setBlogStatus('sent_request');
		$this->getUser()->getGuardUser()->save();
		$fromwhere = $_SERVER['HTTP_REFERER'];
		$this->redirect($fromwhere);
	}
	
	public function executePricerequest(sfWebRequest $request)
	{
		$this->getUser()->getGuardUser()->setBalance('-1');
		$this->getUser()->getGuardUser()->save();
		$fromwhere = $_SERVER['HTTP_REFERER'];
		$this->redirect($fromwhere);
	}

	protected function processForm(sfWebRequest $request, sfForm $form, $url = 'account/edit')
	{
		$u = $request->getParameter('sf_guard_user');

		// Проверка уникальности юзернейма на форуме

		$st = Doctrine_Manager::getInstance()->getCurrentConnection();
		$alias = "'".$u['nickname']."'";
		$email = "'".$u['username']."'";
		$query = "SELECT * FROM for_users WHERE username LIKE $alias AND email NOT LIKE $email";
		$tmp = $st->execute($query);
		$user = $tmp->fetchAll();

		if($u['image_delete'])
		$u['image'] = NULL;

		$arg1 = $request->getParameter($form->getName());

		if(count($user) == 1)
		{
			$arg1['nickname'] = " ";
		}

		$form->bind($arg1,$request->getFiles($form->getName()));

		if ($form->isValid()) {

			define('FORUM', 1);

			// Saving to getting password_salt

			$account = $form->save();

			$salt = random_key(12);
			$password_hash = forum_hash($u['password'], $salt);

			// add user to db
			$user_info = array(
				'username'				=>  addslashes($u['nickname']),
				'group_id'				=>	'3',
				'salt'					=>	addslashes($salt),
				'password'				=>	addslashes($form->getObject()->getPassword()),
				'password_hash'			=>	addslashes($password_hash),
				'email'					=>	addslashes($form->getObject()->getUsername()),
				'email_setting'			=>	'1',
				'timezone'				=>	'0',
				'dst'					=>	'0',
				'language'				=>	'Russian',
				'style'					=>	'Oxygen',
				'registered'			=>	time(),
				'registration_ip'		=>	get_remote_address(),
				'activate_key'			=>	'NULL',
				'require_verification'	=>	'NULL',
				'notify_admins'			=>	'NULL'
				);

				$con = Doctrine_Manager::getInstance()->connection();
				$query = 'INSERT INTO for_users (username, group_id, password, email, email_setting, timezone, dst, language, style, registered, registration_ip, last_visit, salt, activate_key) VALUES ( \''.$user_info['username'].'\', '.$user_info['group_id'].', \''.$user_info['password_hash'].'\', \''.$user_info['email'].'\', '.$user_info['email_setting'].', '.floatval($user_info['timezone']).', '.$user_info['dst'].', \''.$user_info['language'].'\', \''.$user_info['style'].'\', '.$user_info['registered'].', \''.$user_info['registration_ip'].'\', '.$user_info['registered'].', \''.$user_info['salt'].'\', '.$user_info['activate_key'].')';
				$st = $con->execute($query);

				$conn = Doctrine_Manager::getInstance()->connection();
				$query = 'SELECT * FROM for_users WHERE username = \''.$form->getObject()->getUsername().'\'';
				$st = $conn->execute($query);
				$ne = $st->fetchAll();

				$new_uid = $ne[0]['id'];

				$expire = time() + 3600000;

				$value = base64_encode($new_uid.'|'.$password_hash.'|'.$expire.'|'.sha1($salt.$password_hash.forum_hash($expire, $salt))) ;

				setcookie($cookie_name, $value, $expire, $cookie_path, $cookie_domain, $cookie_secure, true);

				if ($url == 'account/edit')
				{
					$this->getUser()->signin($account);
					$this->getUser()->setFlash('saved',true);
					$group_updating_result = sfGuardUserGroup::updateUserGroup($account);
				}
				$this->redirect($url);
		}
	}

	protected function doSomething($categ, $parent, $pos, $level, $expand)
	{
		$out="";
		for ($i = $pos; $i < count($categ); $i++)
		{
			if($categ[$i]->getParentId() == $parent)
			{
				if($i != count($categ) - 1)
				{
					$undercat = $this->doSomething($categ, $categ[$i]->getId(), $i+1, $level+1, $expand);

					if(strlen(trim($undercat))>2)
					$out = $out.'<li style="cursor:pointer;" ><span>'.$categ[$i]->getTitle().'</span><ul style="padding-left:20px;>'.$undercat.'</ul></li>';
					else
					$out = $out.'<li style="list-style:none"><span>'.$categ[$i]->getTitle(). '   id: '.$categ[$i]->getId().'</span></li>';
				}
				else
				{
					$out = $out.'<li style="list-style:none"><span>'.$categ[$i]->getTitle(). '   id: '.$categ[$i]->getId().'</span></li>';
				}
			}
		}
		return $out;
	}
}
